package com.pzl.bezier;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by Administrator on 2016-04-21.
 */
public class BezierView extends View {
    private Paint mPaint;
    private Path mPath;
    private int mNewY1, mNewX1, mNewY2, mNewX2, mDownY, mDownX;
    private int mStartX, mStartY, mEndX, mEndY;

    public BezierView(Context context) {
        super(context);
        mPaint = new Paint();
        mPath = new Path();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.RED);
        mPaint.setStrokeWidth(2);
        mStartX = 0;
        mStartY = 0;
        mEndX = 900;
        mEndY = 900;
        mPath.moveTo(mStartX, mStartY);
    }

    public BezierView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BezierView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPath(mPath, mPaint);
        super.onDraw(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                mPath.reset();
                mNewX1 = (int) event.getX(0);
                mNewY1 = (int) event.getY(0);
                if (event.getPointerCount() == 1) {
                    mPath.quadTo(mNewX1, mNewY1, mEndX, mEndY);//[二阶]开始点自动设为（0，0），（x1,y1）为控制点，（x2,y2）为终点
                } else if (event.getPointerCount() == 2) {
                    mNewX2 = (int) event.getX(1);
                    mNewY2 = (int) event.getY(1);
                    mPath.cubicTo(mNewX1, mNewY1, mNewX2, mNewY2, mEndX, mEndY);//[三阶]开始点自动设为（0，0），（x1,y1）和（x2,y2）为控制点，（x3,y3）为终点
                }
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        invalidate();
        return true;
    }
}
